<template>
  <div class="login-container">
    <div class="login-box">
      <div class="title">MES 系统登录</div>

      <el-form :model="loginForm" :rules="rules" ref="loginFormRef">
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            prefix-icon="User"
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleLogin" class="login-btn">
            登录
          </el-button>
        </el-form-item>

        <div class="options">
          <el-link type="primary" @click="goToRegister">注册账号</el-link>
          <el-link type="primary">忘记密码？</el-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { useTokenStore } from "@/stores/modules/user";
import { login } from "@/apis/api";
import { ElMessage } from "element-plus";

const router = useRouter();
const tokenStore = useTokenStore();
const loginFormRef = ref(null);

const loginForm = reactive({
  username: "",
  password: "",
});

const rules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 20, message: "长度在 3 到 20 个字符", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" },
  ],
};

const handleLogin = async () => {
  if (!loginFormRef.value) return;
  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const success = await tokenStore.login({
          username: loginForm.username,
          password: loginForm.password,
        });

        if (success) {
          ElMessage.success("登录成功");
          router.push("/");
        }
      } catch (error) {
        console.error("Login error:", error);
        ElMessage.error("登录失败，请稍后重试");
      }
    }
  });
};

const goToRegister = () => {
  router.push("/register");
};
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
}

.login-box {
  width: 400px;
  padding: 40px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.title {
  text-align: center;
  font-size: 24px;
  color: #303133;
  margin-bottom: 30px;
}

.login-btn {
  width: 100%;
}

.options {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}
</style>
